package co.yixiang.yshop.module.crm.job;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.NumberUtil;
import co.yixiang.yshop.framework.common.enums.ShopCommonEnum;
import co.yixiang.yshop.framework.quartz.core.handler.JobHandler;
import co.yixiang.yshop.framework.redis.util.redis.RedisUtil;
import co.yixiang.yshop.module.crm.dal.dataobject.crmclues.CrmCluesDO;
import co.yixiang.yshop.module.crm.dal.mysql.crmclues.CrmCluesMapper;
import co.yixiang.yshop.module.crm.enums.CluesStatusEnum;
import co.yixiang.yshop.module.crm.service.crmclues.CrmCluesService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自动线索公海任务
 * 根据配置的未跟进天数和未转化天数，自动将符合条件的线索放入公海
 */
@Component
@Slf4j
public class CluesAutoJob implements JobHandler {
    @Resource
    private CrmCluesMapper cluesMapper;
    @Resource
    private CrmCluesService cluesService;

    @Override
    public String execute(String param) {
        log.info("====== 线索公海自动任务开始执行 ======");
        
        // 从Redis获取配置
        Integer notRecordDay = 7;
        Integer notSuccessDay = 14;
        
        // 检查是否需要执行任务
        if((notRecordDay == null || notSuccessDay == null) || (notRecordDay == 0 && notSuccessDay == 0)){
            log.info("=======线索公海：配置为空或设置为0，不需要执行后面任务=======");
            return "线索公海任务无需执行，配置未启用";
        }
        
        log.info("线索公海任务配置：未跟进天数={}, 未转化天数={}", notRecordDay, notSuccessDay);
        
        // 获取当前时间，用于计算天数差
        LocalDateTime nowTime = LocalDateTime.now();
        final AtomicInteger totalCount = new AtomicInteger(0);
        final AtomicInteger noFollowCount = new AtomicInteger(0);
        final AtomicInteger noConvertCount = new AtomicInteger(0);
        
        try {
            // 只查询未转客户状态(0)的线索，不再判断ownerUserId
            cluesMapper.selectList(new LambdaQueryWrapper<CrmCluesDO>()
                            .eq(CrmCluesDO::getStatus, CluesStatusEnum.STATUS_0.getValue()),
                    new ResultHandler<CrmCluesDO>() {
                        int count = 0;
                        @Override
                        public void handleResult(ResultContext<? extends CrmCluesDO> resultContext) {
                            CrmCluesDO cluesDO = resultContext.getResultObject();
                            log.debug("线索公海：当前处理第" + (++count) + "条记录ID: " + cluesDO.getId());
                            totalCount.incrementAndGet();
                            
                            boolean needProcess = false;
                            String reason = "";
                            
                            // 处理不跟进 放入公海
                            if(notRecordDay > 0){
                                LocalDateTime followTime = cluesDO.getCreateTime();
                                if(cluesDO.getFollowTime() != null) {
                                    followTime = cluesDO.getFollowTime();
                                }
                                Duration between = LocalDateTimeUtil.between(nowTime, followTime);
                                Long days = Math.abs(between.toDays());
                                
                                // 放入公海
                                if(NumberUtil.compare(days, notRecordDay) > 0){
                                    needProcess = true;
                                    reason = "未跟进天数(" + days + "天)超过设定值(" + notRecordDay + "天)";
                                    noFollowCount.incrementAndGet();
                                }
                            }

                            // 处理长时间未成交/未转化
                            if(!needProcess && notSuccessDay > 0){
                                LocalDateTime createTime = cluesDO.getCreateTime();
                                Duration between = LocalDateTimeUtil.between(nowTime, createTime);
                                Long days = Math.abs(between.toDays());
                                
                                // 放入公海
                                if(NumberUtil.compare(days, notSuccessDay) > 0){
                                    needProcess = true;
                                    reason = "未转化天数(" + days + "天)超过设定值(" + notSuccessDay + "天)";
                                    noConvertCount.incrementAndGet();
                                }
                            }
                            
                            if (needProcess) {
                                try {
                                    cluesService.openClues(cluesDO.getId());
                                    log.info("线索公海：线索ID:{}, 理由:{}, 投入公海成功", cluesDO.getId(), reason);
                                } catch (Exception e) {
                                    log.error("线索公海：线索ID:{}, 理由:{}, 投入公海失败: {}", cluesDO.getId(), reason, e.getMessage());
                                }
                            }
                        }
                    });
        } catch (Exception e) {
            log.error("线索公海任务执行异常", e);
            return "线索公海任务执行异常: " + e.getMessage();
        }
        
        log.info("====== 线索公海自动任务执行完成，总处理：{}条，未跟进放入公海：{}条，未转化放入公海：{}条 ======", 
                totalCount.get(), noFollowCount.get(), noConvertCount.get());
        return String.format("线索公海任务执行完成，总处理：%d条，未跟进放入公海：%d条，未转化放入公海：%d条", 
                totalCount.get(), noFollowCount.get(), noConvertCount.get());
    }
} 